using System.Collections.Generic;

using UFrame.Audio;

using UnityEngine;

public class AudioScaleEffectBehaviour : MonoBehaviour, UFrame.IAlive
{
    //[SerializeField]
    //private AudioSpectrumCtrl m_spectrumCtrl;
    //[SerializeField]
    //private AudioSpectrumClampType m_clampType;
    [Tooltip("How sensitive to the audio are we?")]
    public float sensitivity = 2; // how sensitive is this script to the audio. This value is multiplied by the audio sample data.
    [Tooltip("What objects should we move to create a waveform?\n Usually objects are placed in a line")]
    public List<GameObject> objects; // list of objects to be moved up and down
    public List<int> audioIdexs;
    private List<Vector3> startLocalScale; // the position of each object on game start

    public bool Alive => this;

    // Use this for initialization
    void Start()
    {
        startLocalScale = new List<Vector3>();
        foreach (GameObject obj in objects)
        {
            startLocalScale.Add(obj.transform.localScale);
        }
        Debug.Assert(audioIdexs.Count == objects.Count, "audio index num not equal objs num!");
        TimerAgent.Instance.RegistLoopSafty(this, Refresh, 0.1f, UFrame.Timer.TimerUpdateType.LateUpdate);
    }

    // Update is called once per frame
    bool Refresh()
    {
        float[] audioSamples = AudioVisualManager.GetMeanLevels();
        int index = 0;
        for (int i = 0; i < objects.Count; i++)//for each object
        {
            if (audioIdexs.Count > i)
                index = audioIdexs[i];
            var offset = audioSamples[index] * sensitivity;
            objects[i].transform.localScale = startLocalScale[i] * (1 + offset);
        }
        return false;
    }
}